<template>
  <div class="banner-management">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>轮播图管理</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="handleAdd">新增轮播图</el-button>
      </div>
      
      <el-table
        v-loading="loading"
        :data="bannerList"
        border
        style="width: 100%">
        <el-table-column
          prop="id"
          label="ID"
          width="80">
        </el-table-column>
        <el-table-column
          prop="title"
          label="标题"
          width="180">
        </el-table-column>
        <el-table-column
          label="图片"
          width="180">
          <template slot-scope="scope">
            <el-image 
              style="width: 100px; height: 50px" 
              :src="scope.row.imageUrl" 
              fit="cover"
              :preview-src-list="[scope.row.imageUrl]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column
          prop="linkUrl"
          label="链接地址"
          width="220">
        </el-table-column>
        <el-table-column
          prop="sortOrder"
          label="排序"
          width="80">
        </el-table-column>
        <el-table-column
          label="状态"
          width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="180">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="handlePreview(scope.row)">预览</el-button>
            <el-button type="text" size="small" style="color: #F56C6C" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 轮播图表单对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="bannerForm" :rules="rules" ref="bannerForm" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="bannerForm.title" placeholder="请输入轮播图标题"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="imageUrl">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload">
            <img v-if="bannerForm.imageUrl" :src="bannerForm.imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="image-tip">建议上传尺寸: 750px × 350px</div>
        </el-form-item>
        <el-form-item label="链接地址" prop="linkUrl">
          <el-input v-model="bannerForm.linkUrl" placeholder="请输入点击跳转链接"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="bannerForm.sortOrder" :min="0" :max="999"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="bannerForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 图片预览对话框 -->
    <el-dialog :visible.sync="previewVisible" width="800px" append-to-body>
      <img :src="previewUrl" style="width: 100%;">
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'BannerManagement',
  data() {
    return {
      loading: false,
      bannerList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '新增轮播图',
      bannerForm: {
        id: null,
        title: '',
        imageUrl: '',
        linkUrl: '',
        sortOrder: 0,
        status: 1
      },
      rules: {
        imageUrl: [
          { required: true, message: '请上传轮播图片', trigger: 'change' }
        ]
      },
      uploadUrl: '/api/admin/file/upload',
      previewVisible: false,
      previewUrl: ''
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    fetchData() {
      this.loading = true;
      axios.get(`/api/admin/banner/page?current=${this.currentPage}&size=${this.pageSize}`)
        .then(response => {
          const res = response.data;
          if (res.code === 200) {
            this.bannerList = res.data.records;
            this.total = res.data.total;
          } else {
            this.$message.error(res.msg || '获取轮播图列表失败');
          }
        })
        .catch(error => {
          console.error('获取轮播图列表出错:', error);
          this.$message.error('获取轮播图列表失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    resetForm() {
      this.bannerForm = {
        id: null,
        title: '',
        imageUrl: '',
        linkUrl: '',
        sortOrder: 0,
        status: 1
      };
    },
    handleAdd() {
      this.dialogTitle = '新增轮播图';
      this.resetForm();
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.dialogTitle = '编辑轮播图';
      this.bannerForm = JSON.parse(JSON.stringify(row));
      this.dialogVisible = true;
    },
    handlePreview(row) {
      this.previewUrl = row.imageUrl;
      this.previewVisible = true;
    },
    handleDelete(row) {
      this.$confirm('确认删除该轮播图吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.delete(`/api/admin/banner/delete/${row.id}`)
          .then(response => {
            const res = response.data;
            if (res.code === 200) {
              this.$message.success('删除成功');
              this.fetchData();
            } else {
              this.$message.error(res.msg || '删除失败');
            }
          })
          .catch(error => {
            console.error('删除轮播图出错:', error);
            this.$message.error('删除失败');
          });
      }).catch(() => {
        // 取消删除
      });
    },
    beforeUpload(file) {
      const isImage = file.type.indexOf('image/') === 0;
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },
    handleUploadSuccess(res) {
      if (res.code === 200) {
        this.bannerForm.imageUrl = res.data;
      } else {
        this.$message.error(res.msg || '上传失败');
      }
    },
    submitForm() {
      this.$refs.bannerForm.validate(valid => {
        if (valid) {
          const isEdit = this.bannerForm.id !== null;
          const url = isEdit ? '/api/admin/banner/update' : '/api/admin/banner/add';
          const method = isEdit ? 'put' : 'post';
          
          axios[method](url, this.bannerForm)
            .then(response => {
              const res = response.data;
              if (res.code === 200) {
                this.$message.success(isEdit ? '更新成功' : '添加成功');
                this.dialogVisible = false;
                this.fetchData();
              } else {
                this.$message.error(res.msg || (isEdit ? '更新失败' : '添加失败'));
              }
            })
            .catch(error => {
              console.error(isEdit ? '更新轮播图出错:' : '添加轮播图出错:', error);
              this.$message.error(isEdit ? '更新失败' : '添加失败');
            });
        } else {
          return false;
        }
      });
    }
  }
};
</script>

<style scoped>
.banner-management {
  padding: 20px;
}
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 100px;
  display: block;
}
.image-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style> 